package yw.substart.example.service;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author lwq
 * @date 2018/4/9
 * @comment
 */
@Aspect
@Component
public class SystemLogConfig {

    private final Logger logger = LoggerFactory.getLogger(SystemLogConfig.class);

    @Pointcut("execution(public * yw.substart.example.controller..*.*(..))")
    public void point(){}

    @Before("point()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        if(!"setRequest".equals(joinPoint.getSignature().getName())) {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            logger.info("URL : " + request.getRequestURL().toString());
            logger.info("HTTP_METHOD : " + request.getMethod());
            logger.info("IP : " + request.getRemoteAddr());
            logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
            Object[] objects = joinPoint.getArgs();
            for(Object object : objects) {
                if(object instanceof HttpServletRequest) continue;
                logger.info("ARGS : " + JSON.toJSONString(object));
            }
        }
    }

//    @AfterReturning(returning = "ret", pointcut = "point()")
//    public void doAfterReturning(Object ret) throws Throwable {
//        logger.info("RESPONSE : " + JSON.toJSONString(ret));
//    }

}
